package com.qf.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;

import com.qf.pojo.DtsAdmin;
import com.qf.service.AdminService;
import com.qf.util.ResponseUtil;
import com.qf.util.bcrypt.BCryptPasswordEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin("*")
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;


    /**
     * 管理员用户分页查询
     * @param page 当前页
     * @param limit 分页
     * @param username 管理员姓名
     * @param sort 排序字段
     * @param order 排序方式
     * @return
     */
    @RequestMapping("/list")
    public Object list(Integer page, Integer limit,String username, String sort,String order){

        IPage<DtsAdmin> pageResult = adminService.findByPage(page, limit, username, sort, order);

        Map<String,Object> data = new HashMap<>();

        data.put("total",pageResult.getTotal());
        data.put("items",pageResult.getRecords());

        return ResponseUtil.ok(data);
    }

    /**
     * 新建管理员
     * @param admin
     * @return
     */
    @RequestMapping("/create")
    public Object create(@RequestBody DtsAdmin admin){
        admin = adminService.insert(admin);

        return ResponseUtil.ok(admin);
    }

    /**
     * 删除管理员
     * @param admin
     * @return
     */
    @RequestMapping("/delete")
    public Object delete(@RequestBody DtsAdmin admin){
        Integer id = admin.getId();
        if (id == null){
            return ResponseUtil.badArgument();
        }
        adminService.deleteById(id);

        return ResponseUtil.ok();
    }

    @RequestMapping("/update")
    public Object update(@RequestBody DtsAdmin admin){
        Integer id = admin.getId();
        if (id == null){
          return   ResponseUtil.badArgument();
        }

        String password = admin.getPassword();
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encode = encoder.encode(password);
        admin.setPassword(encode);

        int update = adminService.updateById(admin);
        if (update == 0){
            return ResponseUtil.updatedDataFailed();
        }

        return ResponseUtil.ok(admin);
    }

}
